package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.entity.SwStElectronicReceipt;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.service.SwStElectronicReceiptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 电子回执单
 *
 * @author songtuo
 * @date 2020-07-13 13:34:08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstelectronicreceipt")
@Api(value = "swstelectronicreceipt", tags = "电子回执单管理")
@Slf4j
public class SwStElectronicReceiptController {

    private final SwStElectronicReceiptService swStElectronicReceiptService;

    private final SystemUserService systemUserService;

    /**
     * 分页查询
     *
     * @param page                  分页对象
     * @param swStElectronicReceipt 电子回执单
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStElectronicReceiptPage(Page page, SwStElectronicReceipt swStElectronicReceipt) {
        SwStElectronicReceipt swStElectronicReceiptObj = ObjectUtils.getDefaultObj(SwStElectronicReceipt.class);
        swStElectronicReceipt.setLineCode(swStElectronicReceiptObj.getLineCode());
        swStElectronicReceipt.setStationCode(swStElectronicReceiptObj.getStationCode());
        List<String> dateCondition = swStElectronicReceipt.getDates1();
        QueryWrapper queryWrapper = Wrappers.query(swStElectronicReceipt);
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.between("account_time", dateCondition.get(0), dateCondition.get(1));
        }
        queryWrapper.orderByDesc("ACCOUNT_TIME");
        return R.ok(swStElectronicReceiptService.page(page, queryWrapper));
    }

    /**
     * 通过id查询电子回执单
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStElectronicReceiptService.getById(id));
    }

//    /**
//     * 新增电子回执单
//     * @param swStElectronicReceipt 电子回执单
//     * @return R
//     */
//    @ApiOperation(value = "新增电子回执单", notes = "新增电子回执单")
//    @SysLog("新增电子回执单" )
//    @PostMapping
//    @PreAuthorize("@pms.hasPermission('generator_swstelectronicreceipt_add')" )
//    public R save(@RequestBody SwStElectronicReceipt swStElectronicReceipt) {
//        return R.ok(swStElectronicReceiptService.save(swStElectronicReceipt));
//    }

    /**
     * 修改电子回执单
     * @param swStElectronicReceipt 电子回执单
     * @return R
     */
    @ApiOperation(value = "修改电子回执单", notes = "修改电子回执单")
    @SysLog("修改电子回执单" )
    @PutMapping
    //@PreAuthorize("@pms.hasPermission('swstelectronicreceipt_edit')" )
    public R updateById(@RequestBody SwStElectronicReceipt swStElectronicReceipt) {
        return R.ok(swStElectronicReceiptService.updateById(swStElectronicReceipt));
    }

//    /**
//     * 通过id删除电子回执单
//     * @param id id
//     * @return R
//     */
//    @ApiOperation(value = "通过id删除电子回执单", notes = "通过id删除电子回执单")
//    @SysLog("通过id删除电子回执单" )
//    @DeleteMapping("/{id}" )
//    @PreAuthorize("@pms.hasPermission('generator_swstelectronicreceipt_del')" )
//    public R removeById(@PathVariable Integer id) {
//        return R.ok(swStElectronicReceiptService.removeById(id));
//    }

    /**
     * 通过id级联查询售票员结算
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id级联查询电子预览数据", notes = "通过id级联查询电子预览数据")
    @GetMapping("/cascade/{id}")
    public R getCascadeById(@PathVariable("id") Integer id) {
        return R.ok(swStElectronicReceiptService.getCascadeById(id));
    }

    @ApiOperation(value = "导出电子预览数据", notes = "导出电子预览数据")
    @GetMapping("/export")
    public void export(Page page, SwStElectronicReceipt stElectronicReceipt, HttpServletResponse response) {
        List<SwStElectronicReceipt> records = swStElectronicReceiptService.page(page, Wrappers.query(stElectronicReceipt)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStElectronicReceipt record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("电子回执单信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStElectronicReceipt.class).
                    sheet("导出电子预览数据").doWrite(records);
        } catch (IOException e) {
            log.error("导出电子预览数据导出失败");
        }
    }

    /**
     * 批量提交电子预览状态
     *
     * @param ids
     * @param status
     * @return
     */
    @ApiOperation(value = "批量提交电子预览状态", notes = "批量提交电子预览状态")
    @GetMapping("/approval/status")
    @PreAuthorize("@pms.hasPermission('swstelectronicreceipt_approval_status')")
    public R updateApprovalStatus(@RequestParam List<Integer> ids, @RequestParam("status") String status) {
        return R.ok(swStElectronicReceiptService.updateApprovalStatus(ids, status));
    }

}
